# coding: utf-8
import os
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders

# 发送服务器配置
sender_host = 'smtp.exmail.qq.com' #邮件smtp地址
sender_user = ' ' #发送地址
sender_pwd = ' '  #密码
sender_name = '' #发送名称
attach_file = 'zhouzai.docx' #附件名称

# 加载邮件内容：第一行是邮件标题， 第二行是分割线， 第三行之后是邮件正文
default_title = ''
mail_content = ''
if not os.path.exists("邮件内容.txt"):
    print("文件 邮件内容.txt 不存在");
    exit(0);
contentFile = open("邮件内容.txt", encoding="utf-8");
contentLines = contentFile.readlines();
contentFile.close();
if len(contentLines) < 3:
    print("文件 邮件内容.txt 至少三行");
    exit(0);
default_title = contentLines[0];
mail_content = ''.join(contentLines[2:]);

# 加载收件人列表
if not os.path.exists("收件人列表.txt"):
    print("文件 收件人列表.txt 不存在");
    exit(0);
recvFile = open("收件人列表.txt");
recvLines = recvFile.readlines();
recvFile.close();

# 添加附件
# att = MIMEBase('application', 'octet-stream')
# att.set_payload(open(attach_file, 'rb').read())
# att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attach_file));
# encoders.encode_base64(att);

# 发送邮件
# smtp = smtplib.SMTP();
smtp = smtplib.SMTP_SSL(sender_host, 465)
smtp.connect(sender_host);
smtp.login(sender_user, sender_pwd);
for recv in recvLines:
    msg = MIMEMultipart('alternative');
    msg['Subject'] = default_title;
    msg['From'] = sender_name;
    msg['To'] = recv;
    msg.attach(MIMEText(mail_content));
    # msg.attach(att);
    # print(msg.as_string())
    smtp.sendmail(sender_name, recv, msg.as_string());
    print("已发送：" + recv);
smtp.quit();
